<script lang="ts" setup>
import { formatDateTime } from "@/utils/datetime"
import { type ListItem } from "./types"
import { ref } from "vue"
import { reReadMessage } from "@/api/user"

interface Props {
  list: ListItem[]
}

const props = defineProps<Props>()

const cardHeadTitleRef = ref()
const whetherRead = (val: 0 | 1): string => {
  const state = {
    isRead: undefined as unknown as boolean,
    toString() {
      return this.isRead ? "已读" : "未读"
    }
  }
  state.isRead = Boolean(val)
  return `
    <span class="${state.isRead ? "read" : ""}">
      ${state.toString()}
    </span>
  `
}
const handleReReadMsg = (id: number) => {
  reReadMessage({ messageIds: [String(id)] })
}
</script>

<template>
  <el-empty v-if="props.list.length === 0" />
  <el-card
    v-else
    v-for="item in props.list"
    :key="item.id"
    shadow="never"
    class="card-container"
    header-class="card-header"
  >
    <template #header>
      <div>
        <span ref="cardHeadTitleRef">
          <span class="card-title">{{ item.msgTitle }}</span>
          <span class="card-read" v-html="whetherRead(item.msgStatus)" @click="handleReReadMsg(item.id)" />
        </span>
        <div class="card-time">{{ formatDateTime(item.createTime) }}</div>
      </div>
    </template>
    <div class="card-body">
      {{ item.msgContent ?? "No Data" }}
    </div>
  </el-card>
</template>

<style lang="scss" scoped>
.card-container {
  margin-bottom: 10px;
  :deep(.card-header) {
    display: flex;
    width: 100%;
    justify-content: space-between;
    align-items: center;
    padding: 12px 20px;
    .card-title {
      font-weight: bold;
      margin-right: 10px;
    }
    .card-read {
      position: relative;
      font-size: 14px;
      margin-left: 20px;
      color: #6b798e;

      > span {
        color: inherit;
        cursor: pointer;
        &::before {
          content: "•";
          position: absolute;
          left: -10px;
          color: currentColor;
        }
        &.read {
          color: #68945c;
        }
      }
    }
    .card-time {
      font-size: 12px;
      color: var(--el-text-color-secondary);
    }
    .card-avatar {
      display: flex;
      align-items: center;
    }
  }
  .card-body {
    font-size: 12px;
  }
}
</style>
